<template>
  <div class="order-apply-invoice">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, watch, ref,nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({
      xAxisData: [],
      yAxisData: []
    })
  }
})

const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  // 销毁现有实例
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  // 初始化图表
  chartInstance = echarts.init(chartRef.value)
  updateChart()
  
}

const updateChart = () => {
  if (!chartInstance) return

  const option = {
    legend: {
        right: '50px',
        top: '20px',
        data: ['租箱量']
    },
    grid: {
      left: '3%',
      right: '4%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from(props.config.xAxisData),
      // axisLabel: {
      //   interval: 0, // 强制显示所有标签
      //   rotate: 30  // 标签旋转角度，防止重叠
      // }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '租箱量',
      data: Array.from(props.config.yAxisData),
      type: 'bar',
      barWidth: '60%', // 调整柱状图宽度
      itemStyle: {
        color: '#5470c6' // 设置柱状图颜色
      },
      label: {
              show: true, // 显示标签
              position: 'top',
              formatter: '{c}个', // 显示数据值
            }
    }],
    tooltip: {
      trigger: 'axis' // 显示提示框
    }
  }

  chartInstance.setOption(option)
}


onMounted(() => {
  nextTick(() => { 
    initChart()
  })
})

onBeforeUnmount(() => {
  // 清理资源
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 监听配置变化
watch(() => props.config,() => {
    if (!chartInstance) {
      initChart()
    } else {
      updateChart()
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  width: 100%;
  height: 100%;
  
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 400px; // 确保最小高度
  }
}
</style>